package com.example.mobwe_project;

import java.io.File;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.ListIterator;

import android.util.Log;

public class EbookCollection extends LinkedList<Ebook> {

	private static final long serialVersionUID = 1L;
	
	private AppFolder appFolder;
	
	public EbookCollection() {
		Log.d("EbookCollectionClass","Creating a new EbookCollection");
		this.appFolder = new AppFolder();
		Log.d("EbookCollectionClass","Getting the filelist from the appFolder class");
		ArrayList<File> filelist = this.appFolder.getFilelist();
		Log.d("EbookCollectionClass","Getting the list of files (" + filelist.size() + ")");
		if( filelist != null) {
			for( File file : filelist ){
				this.add( new Ebook( file ) );
			}
		}
		Log.d("EbookCollectionClass","Ebook collection created");
	}
	
	public ArrayList<File> getPreviewImages(){
		Log.d("EbookCollectionClass", "Getting preview images " + this.size());
		
		ArrayList<File> filelist = new ArrayList<File>();
		ListIterator<Ebook> itr = this.listIterator();
		File file;
		Log.d("EbookCollectionClass", "Iterator " + itr.nextIndex());
		while( itr.hasNext() ){
			Ebook next = itr.next();
			file = new File( appFolder.getFolder() + "/" + next.getId() + next.getPreview() );
			if( file.exists() ){
				filelist.add( file );
				Log.d("EbookCollectionClass", "Path: " + file.getPath() );
			}			
			Log.d("EbookCollectionClass", "Path2: " + file.getPath() );
		}
		Log.d("EbookCollectionClass", "Preview images were fetched");
		return filelist;
	}
	
	public ArrayList<Ebook> getEbooks(){
		Iterator<Ebook> itr = this.iterator();
		ArrayList<Ebook> list = new ArrayList<Ebook>();
		Ebook next;
		while(itr.hasNext()){
			next = itr.next();
			list.add( next );
		}
		return list;
	}
	
	public Ebook getEbookById( String id ){
		
		for( Ebook ebook : this ){
			if( ebook.getId().equals( id ) ){
				Log.d("EbookCollectionClass", "Ebook with id " + id + " was found");
				return ebook;
			}
			Log.d("EbookCollectionClass", "It wasn't this one (" + ebook.getId() + " != " + id + ")");
		}
		return new Ebook();
	}
}
